from flask import Blueprint, request, jsonify
from flask_cors import cross_origin
from db import db
from models import FeedingRecord, BabyInfo, FoodCategory, FoodOption, ComplementaryFoodRecord, ComplementaryFoodDetail
from datetime import datetime, timedelta
import json

api_bp = Blueprint('api', __name__)

@api_bp.route('/records', methods=['GET', 'POST'])
@cross_origin(origins=['http://localhost:5173', 'http://192.168.1.5:5173', 'http://localhost:5000'], methods=['GET', 'POST'], supports_credentials=True)
def handle_records():
    if request.method == 'GET':
        records = FeedingRecord.query.order_by(FeedingRecord.date.desc(), FeedingRecord.time.desc()).all()
        return jsonify([{
            'id': r.id,
            'date': r.date.strftime('%Y-%m-%d'),
            'time': r.time.strftime('%H:%M'),
            'amount': r.amount
        } for r in records])
    
    if request.method == 'POST':
        data = request.json
        new_record = FeedingRecord(
            date=datetime.strptime(data['date'], '%Y-%m-%d').date(),
            time=datetime.strptime(data['time'], '%H:%M').time(),
            amount=data['amount']
        )
        db.session.add(new_record)
        db.session.commit()
        return jsonify({'id': new_record.id}), 201

@api_bp.route('/records/<int:id>', methods=['DELETE', 'PUT'])
@cross_origin(origins=['http://localhost:5173', 'http://192.168.1.5:5173', 'http://localhost:5000'], methods=['DELETE', 'PUT'], supports_credentials=True)
def handle_record(id):
    record = FeedingRecord.query.get_or_404(id)
    
    if request.method == 'DELETE':
        db.session.delete(record)
        db.session.commit()
        return jsonify({'success': True})

@api_bp.route('/complementary-food-stats', methods=['GET'])
@cross_origin(origins=['http://localhost:5173', 'http://192.168.1.5:5173', 'http://localhost:5000'], methods=['GET'], supports_credentials=True)
def get_complementary_food_stats():
    """获取辅食统计数据"""
    from sqlalchemy import func
    
    # 获取过敏食物列表
    allergic_foods = db.session.query(
        FoodOption.name,
        FoodCategory.name.label('category_name')
    ).join(
        ComplementaryFoodDetail, FoodOption.id == ComplementaryFoodDetail.food_option_id
    ).join(
        ComplementaryFoodRecord, ComplementaryFoodDetail.record_id == ComplementaryFoodRecord.id
    ).join(
        FoodCategory, FoodOption.category_id == FoodCategory.id
    ).filter(
        ComplementaryFoodRecord.acceptance_level == '过敏'
    ).distinct().all()
    
    # 获取最爱食物top5 (喜欢的食物按次数排序)
    favorite_foods = db.session.query(
        FoodOption.name,
        FoodCategory.name.label('category_name'),
        func.count(ComplementaryFoodDetail.id).label('count')
    ).join(
        ComplementaryFoodDetail, FoodOption.id == ComplementaryFoodDetail.food_option_id
    ).join(
        ComplementaryFoodRecord, ComplementaryFoodDetail.record_id == ComplementaryFoodRecord.id
    ).join(
        FoodCategory, FoodOption.category_id == FoodCategory.id
    ).filter(
        ComplementaryFoodRecord.acceptance_level == '喜欢'
    ).group_by(
        FoodOption.id, FoodOption.name, FoodCategory.name
    ).order_by(
        func.count(ComplementaryFoodDetail.id).desc()
    ).limit(5).all()
    
    # 获取不喜欢食物top5 (不喜欢的食物按次数排序)
    disliked_foods = db.session.query(
        FoodOption.name,
        FoodCategory.name.label('category_name'),
        func.count(ComplementaryFoodDetail.id).label('count')
    ).join(
        ComplementaryFoodDetail, FoodOption.id == ComplementaryFoodDetail.food_option_id
    ).join(
        ComplementaryFoodRecord, ComplementaryFoodDetail.record_id == ComplementaryFoodRecord.id
    ).join(
        FoodCategory, FoodOption.category_id == FoodCategory.id
    ).filter(
        ComplementaryFoodRecord.acceptance_level == '不喜欢'
    ).group_by(
        FoodOption.id, FoodOption.name, FoodCategory.name
    ).order_by(
        func.count(ComplementaryFoodDetail.id).desc()
    ).limit(5).all()
    
    return jsonify({
        'allergic_foods': [{'name': food.name, 'category': food.category_name} for food in allergic_foods],
        'favorite_foods': [{'name': food.name, 'category': food.category_name, 'count': food.count} for food in favorite_foods],
        'disliked_foods': [{'name': food.name, 'category': food.category_name, 'count': food.count} for food in disliked_foods]
    })

@api_bp.route('/food-category-distribution', methods=['GET'])
@cross_origin(origins=['http://localhost:5173', 'http://192.168.1.5:5173', 'http://localhost:5000'], methods=['GET'], supports_credentials=True)
def get_food_category_distribution():
    """获取30天内食物类型分布"""
    from datetime import datetime, timedelta
    from sqlalchemy import func
    
    # 计算30天前的日期
    thirty_days_ago = datetime.now().date() - timedelta(days=30)
    
    # 查询30天内的食物类型分布
    distribution = db.session.query(
        FoodCategory.name.label('category_name'),
        func.count(ComplementaryFoodDetail.id).label('count')
    ).join(
        FoodOption, FoodCategory.id == FoodOption.category_id
    ).join(
        ComplementaryFoodDetail, FoodOption.id == ComplementaryFoodDetail.food_option_id
    ).join(
        ComplementaryFoodRecord, ComplementaryFoodDetail.record_id == ComplementaryFoodRecord.id
    ).filter(
        ComplementaryFoodRecord.date >= thirty_days_ago
    ).group_by(
        FoodCategory.id, FoodCategory.name
    ).order_by(
        func.count(ComplementaryFoodDetail.id).desc()
    ).all()
    
    return jsonify([{
        'name': item.category_name,
        'value': item.count
    } for item in distribution])
        
    if request.method == 'PUT':
        data = request.json
        record.date = datetime.strptime(data['date'], '%Y-%m-%d').date()
        record.time = datetime.strptime(data['time'], '%H:%M').time()
        record.amount = data['amount']
        db.session.commit()
        return jsonify({
            'id': record.id,
            'date': record.date.strftime('%Y-%m-%d'),
            'time': record.time.strftime('%H:%M'),
            'amount': record.amount
        })

@api_bp.route('/baby', methods=['GET', 'PUT'])
@cross_origin(origins=['http://localhost:5173', 'http://192.168.1.5:5173', 'http://localhost:5000'], methods=['GET', 'PUT'], supports_credentials=True)
def handle_baby_info():
    baby = BabyInfo.query.first()
    
    if request.method == 'GET':
        if not baby:
            return jsonify({'name': '', 'birthdate': ''})
        return jsonify({
            'name': baby.name,
            'birthdate': baby.birthdate.strftime('%Y-%m-%d %H:%M')
        })
    
    if request.method == 'PUT':
        data = request.json
        if not baby:
            baby = BabyInfo(
                name=data['name'],
                birthdate=datetime.strptime(data['birthdate'], '%Y-%m-%d %H:%M')
            )
            db.session.add(baby)
        else:
            baby.name = data['name']
            baby.birthdate = datetime.strptime(data['birthdate'], '%Y-%m-%d %H:%M')
        db.session.commit()
        return jsonify({'success': True})

import os

@api_bp.route('/stats')
@cross_origin(origins=['http://localhost:5173', 'http://192.168.1.5:5173', 'http://localhost:5000'], methods=['GET', 'POST', 'PUT', 'DELETE'], supports_credentials=True)
def get_stats():
    baby = BabyInfo.query.first()
    if not baby or not baby.birthdate:
        return jsonify({'age_days': 0, 'last_feeding': None})
    
    # 计算宝宝年龄
    try:
        if not baby.birthdate:
            age_days = 0
        else:
            if isinstance(baby.birthdate, str):
                birthdate = datetime.strptime(baby.birthdate, '%Y-%m-%d %H:%M')
            else:
                birthdate = baby.birthdate
            # 确保birthdate是datetime对象
            if not isinstance(birthdate, datetime):
                birthdate = datetime.combine(birthdate, datetime.min.time())
            # 计算天数差，考虑时区
            age_days = (datetime.now() - birthdate).days
    except Exception as e:
        print(f"Error calculating age: {e}")
        age_days = 0
    
    # 获取最后一次喂奶记录
    last_record = FeedingRecord.query.order_by(FeedingRecord.date.desc(), FeedingRecord.time.desc()).first()
    last_feeding = None
    if last_record:
        last_feeding = f"{last_record.date} {last_record.time}"
    
    return jsonify({
        'age_days': age_days,
        'last_feeding': last_feeding
    })

# ==================== 辅食相关接口 ====================

@api_bp.route('/food-categories', methods=['GET'])
@cross_origin(origins=['http://localhost:5173', 'http://192.168.1.5:5173', 'http://localhost:5000'], methods=['GET'], supports_credentials=True)
def get_food_categories():
    """获取所有食物类别"""
    categories = FoodCategory.query.all()
    return jsonify([{
        'id': c.id,
        'name': c.name
    } for c in categories])

@api_bp.route('/food-options', methods=['GET', 'POST'])
@cross_origin(origins=['http://localhost:5173', 'http://192.168.1.5:5173', 'http://localhost:5000'], methods=['GET', 'POST'], supports_credentials=True)
def handle_food_options():
    """获取或创建食物选项"""
    if request.method == 'GET':
        category_id = request.args.get('category_id')
        if category_id:
            options = FoodOption.query.filter_by(category_id=category_id).all()
        else:
            options = FoodOption.query.all()
        
        return jsonify([{
            'id': o.id,
            'name': o.name,
            'category_id': o.category_id,
            'category_name': o.category.name,
            'is_custom': o.is_custom
        } for o in options])
    
    if request.method == 'POST':
        data = request.json
        new_option = FoodOption(
            name=data['name'],
            category_id=data['category_id'],
            is_custom=data.get('is_custom', True)
        )
        db.session.add(new_option)
        db.session.commit()
        return jsonify({
            'id': new_option.id,
            'name': new_option.name,
            'category_id': new_option.category_id,
            'is_custom': new_option.is_custom
        }), 201

@api_bp.route('/food-options/<int:id>', methods=['DELETE', 'PUT'])
@cross_origin(origins=['http://localhost:5173', 'http://192.168.1.5:5173', 'http://localhost:5000'], methods=['DELETE', 'PUT'], supports_credentials=True)
def handle_food_option(id):
    """删除或更新食物选项"""
    option = FoodOption.query.get_or_404(id)
    
    if request.method == 'DELETE':
        # 只允许删除自定义选项
        if not option.is_custom:
            return jsonify({'error': '不能删除系统预设选项'}), 400
        
        # 检查是否有相关的辅食记录
        related_details = ComplementaryFoodDetail.query.filter_by(food_option_id=id).first()
        if related_details:
            return jsonify({'error': '该食物已被记录使用，无法删除。请先删除相关记录。'}), 400
        
        db.session.delete(option)
        db.session.commit()
        return jsonify({'success': True})
    
    if request.method == 'PUT':
        data = request.json
        option.name = data['name']
        option.category_id = data['category_id']
        db.session.commit()
        return jsonify({
            'id': option.id,
            'name': option.name,
            'category_id': option.category_id,
            'is_custom': option.is_custom
        })

@api_bp.route('/complementary-food-records', methods=['GET', 'POST'])
@cross_origin(origins=['http://localhost:5173', 'http://192.168.1.5:5173', 'http://localhost:5000'], methods=['GET', 'POST'], supports_credentials=True)
def handle_complementary_food_records():
    """获取或创建辅食记录"""
    if request.method == 'GET':
        records = ComplementaryFoodRecord.query.order_by(
            ComplementaryFoodRecord.date.desc(), 
            ComplementaryFoodRecord.time.desc()
        ).all()
        
        result = []
        for record in records:
            record_data = {
                'id': record.id,
                'date': record.date.strftime('%Y-%m-%d'),
                'time': record.time.strftime('%H:%M'),
                'acceptance_level': record.acceptance_level,
                'notes': record.notes,
                'details': []
            }
            
            for detail in record.details:
                record_data['details'].append({
                    'id': detail.id,
                    'food_name': detail.food_option.name,
                    'food_category': detail.food_option.category.name
                })
            
            result.append(record_data)
        
        return jsonify(result)
    
    if request.method == 'POST':
        data = request.json
        
        # 创建主记录
        new_record = ComplementaryFoodRecord(
            date=datetime.strptime(data['date'], '%Y-%m-%d').date(),
            time=datetime.strptime(data['time'], '%H:%M').time(),
            acceptance_level=data['acceptance_level'],
            notes=data.get('notes', '')
        )
        db.session.add(new_record)
        db.session.flush()  # 获取ID
        
        # 创建详情记录
        for detail_data in data['details']:
            detail = ComplementaryFoodDetail(
                record_id=new_record.id,
                food_option_id=detail_data['food_option_id']
            )
            db.session.add(detail)
        
        db.session.commit()
        return jsonify({'id': new_record.id}), 201

@api_bp.route('/complementary-food-records/<int:id>', methods=['DELETE', 'PUT'])
@cross_origin(origins=['http://localhost:5173', 'http://192.168.1.5:5173', 'http://localhost:5000'], methods=['DELETE', 'PUT'], supports_credentials=True)
def handle_complementary_food_record(id):
    """删除或更新辅食记录"""
    record = ComplementaryFoodRecord.query.get_or_404(id)
    
    if request.method == 'DELETE':
        db.session.delete(record)
        db.session.commit()
        return jsonify({'success': True})
    
    if request.method == 'PUT':
        data = request.json
        
        # 更新主记录
        record.date = datetime.strptime(data['date'], '%Y-%m-%d').date()
        record.time = datetime.strptime(data['time'], '%H:%M').time()
        record.acceptance_level = data['acceptance_level']
        record.notes = data.get('notes', '')
        
        # 删除旧的详情记录
        ComplementaryFoodDetail.query.filter_by(record_id=record.id).delete()
        
        # 创建新的详情记录
        for detail_data in data['details']:
            detail = ComplementaryFoodDetail(
                record_id=record.id,
                food_option_id=detail_data['food_option_id']
            )
            db.session.add(detail)
        
        db.session.commit()
        
        # 返回更新后的记录
        record_data = {
            'id': record.id,
            'date': record.date.strftime('%Y-%m-%d'),
            'time': record.time.strftime('%H:%M'),
            'acceptance_level': record.acceptance_level,
            'notes': record.notes,
            'details': []
        }
        
        for detail in record.details:
            record_data['details'].append({
                'id': detail.id,
                'food_name': detail.food_option.name,
                'food_category': detail.food_option.category.name
            })
        
        return jsonify(record_data)